package org.ecype.diego.sqlite;

import org.ecype.diego.Contract;
import org.ecype.diego.Entity;
import org.ecype.diego.EntityToSqlConverter;
import org.ecype.diego.UpdateCallback;

import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHelper extends SQLiteOpenHelper {

	private Contract contract;

	public DatabaseHelper(Context context, Contract contract) {
		super(context, contract.getDbFileName(), null, contract.getVersion());
		this.contract = contract;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		EntityToSqlConverter entityToSqlConverter = new EntityToSqlConverter();
		for (Entity entry : contract) {
			String sql = entityToSqlConverter.getCreateTableSql(entry);
			Log.d("SQL", sql);
			db.execSQL(sql);
		}
	}

	@Override
	public void onOpen(SQLiteDatabase db) {
		super.onOpen(db);
		// Работает только с 2.2
		// if (!db.isReadOnly()) {
		// // Enable foreign key constraints
		// db.execSQL("PRAGMA foreign_keys=ON;");
		// }
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        for (Entity entry : contract) {
        	UpdateCallback updateCallback = entry.getUpdateCallback();
      		updateCallback.onUpdate(entry, db, oldVersion, newVersion);
        }
	}

	public void dump() {
		SQLiteDatabase db = getReadableDatabase();
		for (Entity entry : contract) {
			String table = entry.getName();
			Log.v("SQL", table);
			Cursor cursor = db.query(table, null, null, null, null, null, null);
			DatabaseUtils.dumpCursor(cursor);
			cursor.close();
		}

	}
}
